#!/bin/bash

load inquirer

help() {
  echo "Usage:"
  echo "  zcompose up <service_name> [options...]"
}

core() {
  if [ "$1" = "" ] || [ "$1" = "-h" ] || [ "$1" = "--help" ]; then
    help
    exit 0
  fi

  local default_command=sh

  local service_name=$1
  local sub_service_name=""
  local _command=${@:2}
  local command=${_command:-$default_command}

  log::debug "[service][exec] command: $command"

  if [ "$(string::match $service_name :)" = "true" ]; then
    local splits=($(string::split : $service_name))
    service_name=${splits[0]}
    sub_service_name=${splits[1]}
  fi

  if [ -z "$sub_service_name" ]; then
    # service::run $service_name ps $args
    local services=$(service::run $service_name ps --services)
    local count=$(echo $services | wc -w)
    log::debug "[service][exec] select services: $services, count: $count"

    # No service found, maybe not start
    if [ $count -eq 0 ]; then
      log::error "you should start service first"
      exit 1
    fi

    # Found only one service
    if [ $count -eq 1 ]; then
      service::run $service_name exec $services $command
      exit 0
    fi

    local services_for_select=($services)
    inquirer::select "Select an service ?" services_for_select select_service
    log::debug "[service][exec] select service: $select_service"

    sub_service_name=$select_service
  fi

  service::run $service_name exec $sub_service_name $command
}

run() {
  core $@
}

run $@
